
package stcu;

import stcu.control.*;
import stcu.forms.*;
import stcu.robjects.*;
import com.nvlled.route.*;
import javax.swing.SwingUtilities;
import java.awt.Window;

public class Client {

    private Client self = this;
    private ObjectRouter router;
    private ClientAuth auth;
    private Prober prober;
    private GroupAccess access;
    private Pinger pinger;

    LoginForm loginForm;
    MainForm mainForm;
	//ListServerForm listServerForm;

    public Client(ObjectRouter router) {
        this.router = router;
        init();
    }

    private void init() {
        auth = new ClientAuth(router);
        prober = new Prober(router);
        access = new GroupAccess(router);
		
		//listServerForm = new ListServerForm(prober);

        loginForm = new ControlledLoginForm(auth);
        auth.addListener(new Handler());
    }

    public ObjectRouter getRouter() {
        return router;
    }

    public ClientAuth getAuth() {
        return auth;
    }

    public GroupAccess getAccess() {
        return access;
    }

    public void start() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
				//listServerForm.setVisible(true);
				loginForm.setVisible(true);
		
            }
        });
        new Thread(prober).start(); // start probing for servers
    }

    public static void main(String args[]) throws Exception { 
        ObjectRouter router = new ObjectRouter();
        Client c = new Client(router);
        c.start();

        router.bind();
    }

    class Handler implements ClientAuth.Listener {
        public void fail(String msg) { }

        public void success(Login.Status status) {
            prober.stop();
            pinger = new Pinger(router);
            Account account = auth.getAccount();
            String id = DefaultGroup.DEFAULT_ID+"";
            Group defaultGroup = 
                access.join(account, id);

            mainForm = new ControlledMainForm(defaultGroup, self);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    mainForm.setVisible(true);
                    loginForm.setVisible(false);
                }
            });
        }

        public void logout() {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    for (Window w: Window.getWindows()) {
                        w.setVisible(false);
                    }
                }
            });
            router.purgeRoutes();
            pinger.stop();
            init();
            start();
        }
    }

    class LogoutHook implements Runnable {
        public void run() {
        }
    }

}

